package com.czy.owner.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.entity.CommentGoodsModel;
import com.czy.owner.entity.OrderItemsBean;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.ActionSheetDialog;
import com.czy.owner.widget.FullyGridLayoutManager;
import com.easyrecycleview.adapter.BaseViewHolder;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.FunctionOptions;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by wangyang on 2017/4/20 0020.
 */
public class OrderEvaluateAdapter extends RecyclerArrayAdapter<OrderItemsBean> {
    private Context context;
    private Activity activity;
    //    图片选择相关

    private int selectMode = FunctionConfig.MODE_MULTIPLE;
    private int maxSelectNum = 5;// 图片最大可选数量
    private int selectType = FunctionConfig.TYPE_IMAGE;
    private int copyMode = FunctionConfig.CROP_MODEL_DEFAULT;
    private boolean enablePreview = true;
    private boolean isPreviewVideo = true;
    private boolean selectImageType = false;
    private int cropW = 0;
    private int cropH = 0;
    private int maxB = 0;
    private int compressW = 0;
    private int compressH = 0;
    private boolean isCompress = false;
    private boolean isCheckNumMode = true;
    private int compressFlag = 1;// 1 系统自带压缩 2 luban压缩
    private int themeStyle;
    private int previewColor, completeColor, previewBottomBgColor, previewTopBgColor, bottomBgColor, checkedBoxDrawable;
    private boolean clickVideo = false;
    private boolean isFlagCamera = true;

    public OrderEvaluateAdapter(Context context, Activity activity) {
        super(context);
        this.context = context;
        this.activity = activity;

    }

    @Override
    public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
        return new OrderEvaluateAdapter.OrderEvaluateViewHolder(parent);

    }

    class OrderEvaluateViewHolder extends BaseViewHolder<OrderItemsBean> {
        private ImageView imgProduct;
        private TextView tvProductDescription;
        private TextView tvProductPrice;
        private TextView tvProductCount;
        private RatingBar ratingbarEvaluate;
        private EditText etEvaluateNote;
        private RecyclerView recyclerView;
        private GridImageAdapter adapter;
        private TextView tvSpac;
        private List<LocalMedia> selectMedia = new ArrayList<>();

        public OrderEvaluateViewHolder(ViewGroup parent) {
            super(parent, R.layout.item_comment_goods);
            imgProduct = $(R.id.img_product);
            tvProductDescription = $(R.id.tv_product_description);
            tvProductPrice = $(R.id.tv_product_price);
            tvProductCount = $(R.id.tv_product_count);
            ratingbarEvaluate = $(R.id.ratingbar_evaluate);
            etEvaluateNote = $(R.id.et_evaluate_note);
            recyclerView = $(R.id.recycler);
            tvSpac = $(R.id.tv_spac);
            selectMedia.clear();
        }


        @Override
        public void setData(final OrderItemsBean data) {
            tvProductDescription.setText(data.getItemName());
            tvProductPrice.setText("￥" + String.format("%.2f", data.getPrice()));
            tvProductCount.setText("x" + data.getCount());
            tvSpac.setText(data.getSpacValue());
            GlideUtils.loadImage(context, data.getLogo(), imgProduct, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.default_icon, R.mipmap.default_icon);

            //图片选择器相关
            FullyGridLayoutManager manager = new FullyGridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(manager);
            adapter = new GridImageAdapter(context, new GridImageAdapter.onAddPicClickListener() {
                @Override
                public void onAddPicClick(final int type, int position) {
                    switch (type) {
                        case 0:
                            new ActionSheetDialog(context).builder()
                                    .setCancelable(false)
                                    .setCanceledOnTouchOutside(true)
                                    .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                                            new ActionSheetDialog.OnSheetItemClickListener() {
                                                @Override
                                                public void onClick(int which) {
                                                    isFlagCamera = true;
                                                    cameraPhoto(true,data);

                                                }
                                            })
                                    .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                                            new ActionSheetDialog.OnSheetItemClickListener() {
                                                @Override
                                                public void onClick(int which) {
                                                    isFlagCamera = false;
                                                    cameraPhoto(false,data);
                                                }
                                            }).show();
                            break;


                        case 1:
                            // 删除图片
                            selectMedia.remove(position);
                            adapter.notifyItemRemoved(position);
                            break;
                    }
                }
            });
            adapter.setList(selectMedia);
            adapter.setSelectMax(maxSelectNum);
            recyclerView.setAdapter(adapter);


            ratingbarEvaluate.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
                @Override
                public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {

                    data.setStart(ratingBar.getRating());

                }
            });
            etEvaluateNote.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    data.setContent(s + "");
                }
            });

        }


        private void cameraPhoto(boolean model,final OrderItemsBean data) {
            // 进入相册
            themeStyle = ContextCompat.getColor(context, R.color.appThemeColor);
            if (selectImageType) {
                checkedBoxDrawable = R.drawable.select_cb;
            } else {
                checkedBoxDrawable = 0;
            }

            if (isCheckNumMode) {
                // QQ 风格模式下 这里自己搭配颜色
                previewColor = ContextCompat.getColor(context, R.color.blue);
                completeColor = ContextCompat.getColor(context, R.color.blue);
            }

            FunctionOptions options = new FunctionOptions.Builder()
                    .setType(selectType) // 图片or视频 FunctionConfig.TYPE_IMAGE  TYPE_VIDEO
                    .setCropMode(copyMode) // 裁剪模式 默认、1:1、3:4、3:2、16:9
                    .setCompress(isCompress) //是否压缩
                    .setEnablePixelCompress(true) //是否启用像素压缩
                    .setEnableQualityCompress(true) //是否启质量压缩
                    .setMaxSelectNum(maxSelectNum) // 可选择图片的数量
                    .setMinSelectNum(0)// 图片或视频最低选择数量，默认代表无限制
                    .setSelectMode(selectMode) // 单选 or 多选
                    .setShowCamera(false) //是否显示拍照选项 这里自动根据type 启动拍照或录视频
                    .setEnablePreview(enablePreview) // 是否打开预览选项
                    .setEnableCrop(false) // 是否打开剪切选项
                    .setCircularCut(false)// 是否采用圆形裁剪
                    .setPreviewVideo(isPreviewVideo) // 是否预览视频(播放) mode or 多选有效
                    .setCheckedBoxDrawable(checkedBoxDrawable)
                    .setRecordVideoDefinition(FunctionConfig.HIGH) // 视频清晰度
                    .setRecordVideoSecond(60) // 视频秒数
                    .setCustomQQ_theme(0)// 可自定义QQ数字风格，不传就默认是蓝色风格
                    .setGif(false)// 是否显示gif图片，默认不显示
                    .setCropW(cropW) // cropW-->裁剪宽度 值不能小于100  如果值大于图片原始宽高 将返回原图大小
                    .setCropH(cropH) // cropH-->裁剪高度 值不能小于100 如果值大于图片原始宽高 将返回原图大小
                    .setMaxB(maxB) // 压缩最大值 例如:200kb  就设置202400，202400 / 1024 = 200kb
                    .setPreviewColor(previewColor) //预览字体颜色
                    .setCompleteColor(completeColor) //已完成字体颜色
                    .setPreviewBottomBgColor(previewBottomBgColor) //预览图片底部背景色
                    .setPreviewTopBgColor(previewTopBgColor)//预览图片标题背景色
                    .setBottomBgColor(bottomBgColor) //图片列表底部背景色
                    .setGrade(Luban.THIRD_GEAR) // 压缩档次 默认三档
                    .setCheckNumMode(isCheckNumMode)
                    .setCompressQuality(100) // 图片裁剪质量,默认无损
                    .setImageSpanCount(4) // 每行个数
                    .setVideoS(0)// 查询多少秒内的视频 单位:秒
                    .setSelectMedia(selectMedia) // 已选图片，传入在次进去可选中，不能传入网络图片
                    .setCompressFlag(compressFlag) // 1 系统自带压缩 2 luban压缩
                    .setCompressW(compressW) // 压缩宽 如果值大于图片原始宽高无效
                    .setCompressH(compressH) // 压缩高 如果值大于图片原始宽高无效
                    .setThemeStyle(themeStyle) // 设置主题样式
                    .setNumComplete(false) // 0/9 完成  样式
                    .setClickVideo(clickVideo)// 点击声音
                    .create();

            if (model) {
                // 先初始化参数配置 拍照
                PictureConfig.getInstance().init(options).startOpenCamera(activity, new PictureConfig.OnSelectResultCallback() {
                    @Override
                    public void onSelectSuccess(List<LocalMedia> resultList) {
                        // 多选回调
                        if (isFlagCamera) {
                            selectMedia.addAll(resultList);
                        } else {
                            selectMedia = resultList;
                        }

                        MyLog.e("callBack_result", selectMedia.size() + "");
                        LocalMedia media = resultList.get(0);
                        if (media.isCut() && !media.isCompressed()) {
                            // 裁剪过
                            String path = media.getCutPath();
                        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            String path = media.getCompressPath();
                        } else {
                            // 原图地址
                            String path = media.getPath();
                        }
                        if (selectMedia != null) {
                            adapter.setList(selectMedia);
                            adapter.notifyDataSetChanged();

                            List<String> picList = new ArrayList<>();
                            picList.clear();
                            if(selectMedia.size()>0){
                                for (int i=0;i<selectMedia.size();i++){
                                    picList.add(selectMedia.get(i).getPath());
                                    MyLog.e("yang",selectMedia.get(i).getPath());
                                }
                                data.setPicList(picList);

                            }
                        }
                    }

                    @Override
                    public void onSelectSuccess(LocalMedia media) {
                        // 单选回调
                        selectMedia.add(media);
                        if (selectMedia != null) {
                            adapter.setList(selectMedia);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
            } else {
                // 先初始化参数配置，启动相册
                PictureConfig.getInstance().init(options).openPhoto(activity, new PictureConfig.OnSelectResultCallback() {
                    @Override
                    public void onSelectSuccess(List<LocalMedia> resultList) {
                        // 多选回调
                        if (isFlagCamera) {
                            selectMedia.addAll(resultList);
                        } else {
                            selectMedia = resultList;
                        }

                        MyLog.e("callBack_result", selectMedia.size() + "");
                        LocalMedia media = resultList.get(0);
                        if (media.isCut() && !media.isCompressed()) {
                            // 裁剪过
                            String path = media.getCutPath();
                        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            String path = media.getCompressPath();
                        } else {
                            // 原图地址
                            String path = media.getPath();
                        }
                        if (selectMedia != null) {
                            adapter.setList(selectMedia);
                            adapter.notifyDataSetChanged();
                            List<String> picList = new ArrayList<>();
                            picList.clear();
                            if(selectMedia.size()>0){
                                for (int i=0;i<selectMedia.size();i++){
                                    picList.add(selectMedia.get(i).getPath());
                                }
                                data.setPicList(picList);
                            }
                        }
                    }

                    @Override
                    public void onSelectSuccess(LocalMedia media) {
                        // 单选回调
                        selectMedia.add(media);
                        if (selectMedia != null) {
                            adapter.setList(selectMedia);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
            }

        }


    }


}
